<template lang="pug">
.PAGE
    wxc-tab-page(
        ref="wxc-tab-page"
        title-type="text"
        wrap-bg-color="#fff"
        :tab-titles="tabTitles"
        :tab-styles="tabStyles"
        :tab-page-height="tabPageHeight"
        @wxcTabPageCurrentTabSelected="wxcTabPageCurrentTabSelected"
        v-if="permission.has&&permission.open"
    )
        scroller.scroller(
            :style="{height:(tabPageHeight-tabStyles.height)+'px'}"
            v-for="(li,index) in tabList"
            :key="index"
            show-scrollbar="false"
        )

            wxc-pan-item(
                :ext-id="'tab-' + index + '-top'" 
                @wxcPanItemPan="wxcPanItemPan"
                v-for="item in li"
            )
                .item
                    .head
                        text.title {{item.title}} 
                        text.costSum {{item.cost}} 
                    .appLi
                        .app(v-for="app in item.li")
                            .appImg
                                image.ico(:src="'ico://'+app.pkg" style="width:128px;height:128px")
                            .appCost
                                text.costTime {{app.cost}}
                                .costTimeBar(:style="{width:app.w}")
                                text.appName {{app.name}} 
                                text {{app.range_begin}}
                                text {{app.range_end}}
            .theEnd(v-if="li.length")
    .permission(v-else :style="{height:tabPageHeight-100}")
        template(v-if="permission.has")
            text.h1 手机人生
            text.tip 统计手机上度过的人生
            .row 
                text.tip 请先授权
                text.tip.a(@click="permission_request") 查看使用情况
            text.btn.btnPermissionRequest(
                @click="permission_request"
            ) 请您点此启用授权
        template(v-else)
            text.tip 出错了！
            text.tip 该手机不支持查看应用使用情况 
</template>

<style scoped lang="scss">
$blue:#5BF;
.permission{
    background:#f40;
    justify-content:center;
    align-items:center;
    padding:0 50px;
}
.h1{
    font-size:78px;
    color:#555;
    margin-bottom:80px;
}
.btn{
    border-style:solid;
    border-color:darken($blue,25%);
    border-width:3px;
    padding:25px 35px;
    background-color:darken($blue,20%);
    color:#fff;
    font-weight:bold;
}
.row{
    flex-direction:row;
}
.a{
    color:#555;
    border-bottom-width:3px;
    border-bottom-color:#555;
    padding-bottom:5px;
    margin-left:10px;
    border-bottom-style:solid;
}
.btnPermissionRequest{
    margin:80px 0 0;
    font-size:40px;
}
.tip{
    font-size:40px;
    margin:12px 0;
    color:#555;
}
.h1,.tip,.btn{
    font-family:zhs;
}
.theEnd{padding:30px;background-color:#f9f9f9;width:750px}
.appLi{
    border-bottom-width:1px;
    border-bottom-color:#ddd;
    border-bottom-style:dashed;
}
.scroller {
    border-top-width: 1px;
    border-style: solid;
    border-color:#ddd;
}
.item{
    width:750px;
}
.app{
    margin:0 20px 60px;
    height:auto;
    flex-direction:row;
    align-items:stretch;
}
.appCost{
    margin-left:20px;
    width:562px;
}
.head{
    margin:60px 0;
    justify-content:center;
    width:750px;
}
.title, .costSum{
    text-align:center; 
}
.title, .costSum,.appName, .costTime{
    font-family:hind;
}
.title{
    font-size:50px;
    margin-bottom:-10px;
}
.costTime{
    margin:0 0 10px;
    font-size:30px;
}
.appName{
    color:#666;
    font-size:25px;
    margin-top:20px;
}
.costTimeBar{
    background-color:#20B7FC;
    background-image: linear-gradient(to right,$blue, #9df);
    height:15px;
    border-radius:15px;
}
.costSum{
    font-size:33px;
    color:#666;
}
</style>


<script lang="coffee">
[PackageManager, Permission, UsageStats, AndroidOs, Hash] = require(
    '@/util/import'
)(
    weex
    'PackageManager Permission UsageStats AndroidOs Hash'
)

import INTERVAL from '@/const/UsageStatsManager/INTERVAL'
dayjs = require 'dayjs'
import { WxcTabPage, WxcPanItem, BindEnv } from 'weex-ui'
globalEvent = weex.requireModule('globalEvent')
cost_str = require '@/util/time/cost_str'


tabTitles = [
    {
      title: '日'
    }
    {
      title: '周'
    }
    {
      title: '月'
    }
    {
      title: '季'
    }
    {
      title: '年'
    }
]
tabStyles = {
    bgColor: '#FFFFFF'
    titleColor: '#999'
    activeTitleColor: '#000'
    activeBgColor: '#ffffff'
    isActiveTitleBold: false
    width: 150
    height: 80
    fontSize: 30
    fontWeight:200
    hasActiveBottom: true
    activeBottomColor: '#F7BA3F'
    activeBottomHeight: 3
    activeBottomWidth: 60
    textPaddingLeft: 10
    textPaddingRight: 10
}




SETTING = {
    USAGE_ACCESS : "android.settings.USAGE_ACCESS_SETTINGS"
}

EVENT_FG = 'WXApplicationDidBecomeActiveEvent'

###
DAILY : 0
WEEKLY : 1
MONTHLY : 2
YEARLY : 3

日 周 月 季 年

###
usage_li = do ->

    MOVE_TO_BACKGROUND = 2
    APP_NO_ICON = new Set()

    (interval)->
        app_name = (pkg)=>
            if APP_NO_ICON.has(pkg)
                return
            name = @app[pkg]
            if not name
                name = await PackageManager.info(pkg)
                if name
                    @app[pkg] = name
                else
                    APP_NO_ICON.add(pkg)
            return name

        now = new Date()
        offset = now.getTimezoneOffset()*60000
        now = dayjs(now)
        begin_time = now.startOf('day') - 0
        end_time = now - 0
        li = await UsageStats.eventLi(begin_time, end_time)

        pkg_cost = {}
        if li.length
            for [event_type, timestamp, pkg, cls, cost] in li
                if not cls
                    continue
                if event_type == MOVE_TO_BACKGROUND
                    if pkg_cost[pkg]
                        pkg_cost[pkg]+=cost
                    else
                        pkg_cost[pkg]=cost
        else
            @permission_reload()

        _li = []
        cost_sum = 1
        base = 0
        for pkg,cost of pkg_cost
            name = await app_name(pkg)
            if name and cost >= 1000
                if cost > base
                    base = cost
                cost_sum += cost
                _li.push [cost, name, pkg]

        _li.sort((a,b)->b[0]-a[0])

        li = []
        for [cost, name, pkg] in _li
            li.push {
                w:parseInt(cost*562/base)
                name
                pkg
                cost:cost_str(cost)
            }

        return [
            {
                title:now.format('YYYY - MM - DD')
                li
                cost:cost_str(cost_sum)
            }
        ]


            
        #cost_base = _li[0][1]
        #for [pkg, cost, range_begin, range_end] in _li
        #    cost_sum+=cost

        #    range_begin = 
        #    range_end = new Date(range_end-offset).toISOString().slice(0,19).replace("T"," ")
        #            li = []
        #            begin_time = 0
        #            offset = new Date().getTimezoneOffset()*60000

        #            _li = await @query(
        #                INTERVAL.DAILY
        #                begin_time
        #                now-0
        #            )
        #            cost_sum = 0
        #            if _li.length

        #                    li.push {
        #                        name
        #                        pkg
        #                        range_begin
        #                        range_end
        #                        cost:cost_str(cost)
        #                        w:parseInt(562*cost/cost_base)
        #                    }

        #            tabList = [
        #                {
        #                    title:now.format('YYYY - MM - DD')
        #                    li
        #                    cost:cost_str(cost_sum)
        #                }
        #            ]

_TIMTER_UPDATE = undefined

export default {
    components:{
        WxcTabPage
        WxcPanItem
    }
    beforeCreate:->
        require("@/util/font").local("hind zhs")

    data: ->
        {
            tabTitles
            tabStyles
            tabList: []
            tabPageHeight: 1500
            app:{}
            permission:{
                has:1
                open:1
            }
        }

    created: ->
        {deviceHeight, deviceWidth} = weex.config.env
        @tabPageHeight = deviceHeight*750/deviceWidth-100
        @tabList = [].concat(
            ...Array(@tabTitles.length).keys()
        ).map( -> [])
        @refresh()
        return
    
    beforeDestory: ->
        clearInterval(_TIMTER_UPDATE)

    methods:
        refresh:->
            @$nextTick =>
                @$refs['wxc-tab-page'].setPage(0,null,false)

        permission_reload:->
            @permission.has = has = await Permission.has(SETTING.USAGE_ACCESS)
            if has
                @permission.open = open = await UsageStats.ping()
                if open
                    @refresh()

        permission_request: ->
            await Permission.open(SETTING.USAGE_ACCESS)
            @permission_reload()


        wxcTabPageCurrentTabSelected: (e) ->
            index = e.page
            _update = =>
                @$set @tabList, index, await usage_li.call(@, index)
            _update()
            clearInterval(_TIMTER_UPDATE)
            _TIMTER_UPDATE = setInterval(_update, 60000)

        
        wxcPanItemPan: (e) ->
            @$refs['wxc-tab-page'].bindExp e.element
            return
}


</script>
